/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package easyanimation.panel.left;

import easyanimation.frame.CConfig;
import easyanimation.frame.Constant;
import easyanimation.frame.Language;
import easyanimation.frame.MainWindow;
import easyanimation.panel.CCenterPanel;
import easyanimation.panel.CStatusPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author tandn
 */
public class CTabLeft extends JPanel
{
    private CTableModel m_tableModel;
    private JTable m_table;
    private JTextField m_imageField;
    private JButton m_addButton,
            m_deleteButton,
            m_insertButton;
    private int m_totalColumnI;
    private boolean m_hasImageField, m_mustZoomNormalImageWhenAdd, m_isSubTable;
    private Object[] m_dataDefaultObjects; //data default for table row
    private int m_actionI = Constant.TABLE_ACTION_NONE;

    public CTabLeft(String columnNameStrings[],
            int columnsNonEditableIs[],
            int columnsIntegerIs[],
            int columnsIntegerPositiveIs[],
            boolean hasImageField,
            boolean mustZoomNormalImageWhenAdd,
            boolean isSubTable,
            Object[] dataObjects)
    {
        JPanel tabPanelButton; //for tabs
        setLayout(new BorderLayout());
        //update bool variables
        m_hasImageField = hasImageField;
        m_mustZoomNormalImageWhenAdd = mustZoomNormalImageWhenAdd;
        m_isSubTable = isSubTable;
        m_dataDefaultObjects = dataObjects.clone();
        //
        m_tableModel = new CTableModel(columnsNonEditableIs, columnsIntegerIs, columnsIntegerPositiveIs, isSubTable);
        m_tableModel.setColumnNames(columnNameStrings);
        m_tableModel.setData(new String[][]
                {
                });
        m_table = new JTable(m_tableModel);
        //m_table.setPreferredScrollableViewportSize(new Dimension(TOTAL_COLUMN_TABS_PALETTE * COLUMN_WIDTH, 0));
        m_table.setPreferredScrollableViewportSize(new Dimension(Constant.WINDOW_WIDTH_LEFT, 0));
        m_table.setFillsViewportHeight(true);
        m_table.setFont(Constant.OBJ_FONT_PLAIN);
        m_table.getTableHeader().setReorderingAllowed(false); //disable drag and drop column
        //add cell listener
        m_table.getDefaultEditor(Object.class).addCellEditorListener(new CellEditorListener()
        {
            @Override
            public void editingStopped(ChangeEvent event)
            {
                if (m_actionI == Constant.TABLE_ACTION_NONE)
                {
                    m_actionI = Constant.TABLE_ACTION_UPDATE;
                    getCenterPanel().updateFromTable(m_isSubTable, m_actionI, m_table.getSelectedRow(), null);
                    //getCenterPanel().updateAfterModifiedTable(m_bIsSubTable);
                    m_actionI = Constant.TABLE_ACTION_NONE;
                }
            }

            @Override
            public void editingCanceled(ChangeEvent event)
            {
            }
        });
        m_table.setInputVerifier(new InputVerifier()
        {
            @Override
            public boolean verify(JComponent input)
            {
                m_tableModel.storeOldState(m_table.getSelectedRow(), m_table.getSelectedColumn());
                return true;
            }
        });
        //add selection rows listener
        m_table.getSelectionModel().addListSelectionListener(new ListSelectionListener()
        {
            @Override
            public void valueChanged(ListSelectionEvent event)
            {
                if (m_actionI == Constant.TABLE_ACTION_NONE)
                {
                    m_actionI = Constant.TABLE_ACTION_SELECT;
                    getCenterPanel().updateFromTable(m_isSubTable, m_actionI, m_table.getSelectedRow(), null);
                    //getCenterPanel().updateAfterModifiedTable(m_bIsSubTable);
                    m_actionI = Constant.TABLE_ACTION_NONE;
                }
            }
        });
        //align center the first column
        DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer();
        cellRenderer.setHorizontalAlignment(JLabel.CENTER);
        m_table.getColumnModel().getColumn(columnsNonEditableIs[0]).setCellRenderer(cellRenderer);

        add(new JScrollPane(m_table), BorderLayout.CENTER);
        //process the add button
        m_addButton = new JButton(Language.ADD[CConfig.LANGUAGE]);
        m_addButton.setPreferredSize(new Dimension((Language.ADD[CConfig.LANGUAGE].length() + 3) * Constant.CHARACTOR_WIDTH, Constant.COMPONENT_SMALL_HEIGHT));
        m_addButton.setMargin(Constant.OBJ_MARGIN);
        m_addButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                m_actionI = Constant.TABLE_ACTION_ADD;
                if (m_mustZoomNormalImageWhenAdd)
                {
                    getStatusPanel().setZoomForStatus(Constant.ZOOM_NORMAL);
                    getCenterPanel().setZoomForCenter(Constant.ZOOM_NORMAL);
                }
                m_table.changeSelection(m_tableModel.addRow(getDataDefaultObjects()), 0, false, false);
                m_table.updateUI();
                getCenterPanel().updateFromTable(m_isSubTable, m_actionI, -1, null);
                m_actionI = Constant.TABLE_ACTION_NONE;
            }
        });
        tabPanelButton = new JPanel();
        tabPanelButton.add(m_addButton);
        //process the insert button
        m_insertButton = new JButton(Language.INSERT[CConfig.LANGUAGE]);
        m_insertButton.setPreferredSize(new Dimension(Language.INSERT[CConfig.LANGUAGE].length() * Constant.CHARACTOR_WIDTH, Constant.COMPONENT_SMALL_HEIGHT));
        m_insertButton.setMargin(Constant.OBJ_MARGIN);
        m_insertButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                m_actionI = Constant.TABLE_ACTION_INSERT;
                if (m_mustZoomNormalImageWhenAdd)
                {
                    getStatusPanel().setZoomForStatus(Constant.ZOOM_NORMAL);
                    getCenterPanel().setZoomForCenter(Constant.ZOOM_NORMAL);
                }
                int iRow = m_table.getSelectedRow();
                m_table.changeSelection(m_tableModel.insertRow(iRow, getDataDefaultObjects()), 0, false, false);
                m_table.updateUI();
                getCenterPanel().updateFromTable(m_isSubTable, m_actionI, iRow, null);
                m_actionI = Constant.TABLE_ACTION_NONE;
            }
        });
        tabPanelButton.add(m_insertButton);
        //process the delete button
        m_deleteButton = new JButton(Language.DELETE[CConfig.LANGUAGE]);
        m_deleteButton.setPreferredSize(new Dimension(Language.DELETE[CConfig.LANGUAGE].length() * Constant.CHARACTOR_WIDTH, Constant.COMPONENT_SMALL_HEIGHT));
        m_deleteButton.setMargin(Constant.OBJ_MARGIN);
        m_deleteButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                int iRow = m_table.getSelectedRow();
                if (iRow >= 0 && m_table.getRowCount() > 0)
                {
                    m_actionI = Constant.TABLE_ACTION_DELETE;
                    m_tableModel.deleteRow(iRow);
                    if (iRow > 0)
                    {
                        m_table.changeSelection(iRow - 1, 0, false, false);
                    }
                    m_table.updateUI();
                    getCenterPanel().updateFromTable(m_isSubTable, m_actionI, iRow, null);
                    m_actionI = Constant.TABLE_ACTION_NONE;
                }
            }
        });
        tabPanelButton.add(m_deleteButton);
        if (isSubTable)
        {
            //hide the button
            m_addButton.hide();
            m_insertButton.hide();
            m_deleteButton.hide();
        }
        //For image field
        if (m_hasImageField)
        {
            //hide the button
            m_addButton.hide();
            m_insertButton.hide();
            m_deleteButton.hide();
            //arrange for image
            JPanel tabPanelPalette = new JPanel();
            tabPanelPalette.setLayout(new BorderLayout());
            tabPanelPalette.add(tabPanelButton, BorderLayout.CENTER);
            m_imageField = new JTextField(Constant.IMAGE_FIELD_WIDTH);
            m_imageField.setFont(Constant.OBJ_FONT_PLAIN);
            m_imageField.setPreferredSize(new Dimension(Constant.IMAGE_FIELD_WIDTH * Constant.CHARACTOR_WIDTH, Constant.COMPONENT_SMALL_HEIGHT));
            m_imageField.setEditable(false);
            JPanel tabPanelImage = new JPanel();
            tabPanelImage.add(new JLabel(Language.IMAGE[CConfig.LANGUAGE]));
            tabPanelImage.add(m_imageField);
            JButton buttonImage = new JButton(Language.LOAD[CConfig.LANGUAGE]);
            buttonImage.setPreferredSize(new Dimension(Language.LOAD[CConfig.LANGUAGE].length() * Constant.CHARACTOR_WIDTH, Constant.COMPONENT_SMALL_HEIGHT));
            buttonImage.setMargin(Constant.OBJ_MARGIN);
            buttonImage.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent event)
                {
                    loadImage(MainWindow.getInstance());
                }
            });
            tabPanelImage.add(buttonImage);
            tabPanelImage.setBorder(new EtchedBorder(Color.LIGHT_GRAY, Color.GRAY));
            tabPanelPalette.add(tabPanelImage, BorderLayout.SOUTH);
            add(tabPanelPalette, BorderLayout.SOUTH);
        }
        else
        {
            m_imageField = null;
            add(tabPanelButton, BorderLayout.SOUTH);
        }
    }

    public void setShowButtons(boolean isShow)
    {
        if (isShow)
        {
            //show the button
            m_addButton.show();
            m_insertButton.show();
            m_deleteButton.show();
        }
        else
        {
            //hide the button
            m_addButton.hide();
            m_insertButton.hide();
            m_deleteButton.hide();
        }
        updateUI();
    }

    public Object[] getRow(int row)
    {
        int iLength = m_table.getColumnCount();
        Object[] objArrTemp = new Object[iLength];
        for (int col = 0; col < iLength; col++)
        {
            objArrTemp[col] = m_table.getValueAt(row, col);
        }
        return objArrTemp;
    }

    /**
     * set Column Width
     * @param column
     * @param width 
     */
    public void setColumnWidth(int column, int width)
    {
        m_table.getColumnModel().getColumn(column).setPreferredWidth(width);
    }

    /*
     * Load image
     */
    private void loadImage(JFrame window)
    {
        JFileChooser fileBrowser = new JFileChooser(CConfig.STR_DEFAULT_DIRECTORY_IMAGE);
        fileBrowser.setFileFilter(new FileFilter()
        {
            @Override
            public boolean accept(File f)
            {
                return f.isDirectory()
                        || f.getName().toLowerCase().endsWith(Constant.FILE_TYPES_SUPPORTED[0])
                        || f.getName().toLowerCase().endsWith(Constant.FILE_TYPES_SUPPORTED[1]);
            }

            @Override
            public String getDescription()
            {
                return Language.IMAGE_DESCRIPTION[CConfig.LANGUAGE]
                        + "(*." + Constant.FILE_TYPES_SUPPORTED[0]
                        + ", *." + Constant.FILE_TYPES_SUPPORTED[1]
                        + ")";
            }
        });
        int value = fileBrowser.showOpenDialog(window);
        if (value == JFileChooser.APPROVE_OPTION)
        {
            String imagePath = fileBrowser.getCurrentDirectory().toString() + "\\" + fileBrowser.getSelectedFile().getName();
            if (imagePath.toLowerCase().endsWith("jpg")
                    || imagePath.toLowerCase().endsWith("png"))
            {
                m_imageField.setText(imagePath);
                getCenterPanel().setImage(imagePath);
            }
            else
            {
                JOptionPane.showMessageDialog(window, Language.LOAD_IMAGE_NOT_SUPPORT[CConfig.LANGUAGE], Language.ERROR[CConfig.LANGUAGE], JOptionPane.ERROR_MESSAGE);
                return;
            }
            //show the button
            m_addButton.show();
            m_insertButton.show();
            m_deleteButton.show();
            //add the default palette
            Object[] objArrTemp = m_dataDefaultObjects.clone();
            objArrTemp[1] = imagePath;
            m_tableModel.addRow(objArrTemp);
            updateUI();
        }
        else if (value == JFileChooser.CANCEL_OPTION)
        {
            m_imageField.setText("");
        }
        //update ui
        m_imageField.updateUI();
    }

    //<editor-fold defaultstate="collapsed" desc="Function get-set">
    /**
     * @return the m_tableModel
     */
    public CTableModel getTableModel()
    {
        return m_tableModel;
    }

    /**
     * @param m_tableModel the m_tableModel to set
     */
    public void setTableModel(CTableModel m_tableModel)
    {
        this.m_tableModel = m_tableModel;
    }

    /**
     * @return the m_table
     */
    public JTable getTable()
    {
        return m_table;
    }

    /**
     * @param m_table the m_table to set
     */
    public void setTable(JTable m_table)
    {
        this.m_table = m_table;
    }

    /**
     * @return the m_imageField
     */
    public JTextField getImageField()
    {
        return m_imageField;
    }

    /**
     * @param m_imageField the m_imageField to set
     */
    public void setImageField(JTextField m_imageField)
    {
        this.m_imageField = m_imageField;
    }

    /**
     * @return the m_totalColumn
     */
    public int getTotalColumn()
    {
        return m_totalColumnI;
    }

    /**
     * @param m_totalColumn the m_totalColumn to set
     */
    public void setTotalColumn(int m_totalColumn)
    {
        this.m_totalColumnI = m_totalColumn;
    }

    /**
     * @return the m_mustZoomNormalImage
     */
    public boolean isMustZoomNormalImage()
    {
        return m_mustZoomNormalImageWhenAdd;
    }

    /**
     * @param m_mustZoomNormalImage the m_mustZoomNormalImage to set
     */
    public void setMustZoomNormalImage(boolean m_mustZoomNormalImage)
    {
        this.m_mustZoomNormalImageWhenAdd = m_mustZoomNormalImage;
    }

    public CStatusPanel getStatusPanel()
    {
        return MainWindow.getInstance().getStatusPanel();
    }

    public CCenterPanel getCenterPanel()
    {
        return MainWindow.getInstance().getCenterPanel();
    }
    //</editor-fold>

    /**
     * @return the m_bIsSubTable
     */
    public boolean isSubTable()
    {
        return m_isSubTable;
    }

    /**
     * @return the m_iAction
     */
    public int getAction()
    {
        return m_actionI;
    }

    /**
     * @param m_iAction the m_iAction to set
     */
    public void setAction(int m_iAction)
    {
        this.m_actionI = m_iAction;
    }

    /**
     * @return the m_dataDefaultObjects
     */
    public Object[] getDataDefaultObjects()
    {
        return m_dataDefaultObjects.clone();
    }
}

